﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

using DocumentServices.RequestHandlers;
using DocumentServices.Storage.FileSystem;

namespace SampleBrowser.Web
{
    /// <summary>
    /// Document service providing list, retrieval and conversion functionality for XPS documents.
    /// </summary>
    public class DocumentService
        : IHttpHandler
    {
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            try {
                if (context.Request.QueryString.Count == 0) {
                    throw new ArgumentException("Invalid request type");
                }

                // route request to appropiate request handler
                var cmd = context.Request.QueryString[0].ToLowerInvariant();
                IRequestHandler handler = null;

                if (cmd == "convert") {
                    handler = new ConvertToXpsHandler();
                }
                else if (cmd == "list") {
                    handler = new ListDocumentsHandler();
                }
                else {
                    handler = new GetDocumentPartHandler();
                }

                // find documents folder relative to the requested HTTP resource
                var folder = context.Server.MapPath("Documents");
                var store = new FileSystemDocumentStore(folder);

                handler.HandleRequest(context, store);
            }
            catch (Exception e) {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.Write(e.Message);
            }
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}